import { useCallback, useEffect, useState } from "react";
import { getParams, isSameArray, request } from "../../Api/api";
import { getTypeName, getDiffcultLevelName } from "../../Api/name";
import Layout from "../Shared/Layout";
import {
  Button,
  Descriptions,
  Input,
  InputNumber,
  message,
  Select,
} from "antd";
import MyButton from "../../Components/MyButton";
import SelectOptions from "../../Components/Operation/SelectOptions";
import { v4 as uuidv4 } from "uuid";
const QuestionDetail = () => {
  const [question, setQuestion] = useState({});
  const [updatingQuestion, setUpdatingQuestion] = useState({});
  const [isUpdating, setIsUpdating] = useState(false);
  const [options, setOptions] = useState([]);
  const id = getParams("id");
  const bind = useCallback(async () => {
    const res = await request(
      "/question/detail",
      {
        id: id,
      },
      "GET"
    );
    if (res.code >= 0) {
      setQuestion(res.data);
      setOptions(
        res.data.options.map((d) => {
          return { label: d.content, value: d.content, key: uuidv4() };
        })
      );
    }
  }, [id]);
  useEffect(() => {
    async function fetchData() {
      await bind();
    }
    fetchData();
  }, [bind]);
  const isChanged = () => {
    return (
      updatingQuestion.content !== question.content ||
      updatingQuestion.type !== question.type ||
      !isSameArray(
        updatingQuestion.options.map((d) => d.content),
        question.options.map((d) => d.content)
      ) ||
      updatingQuestion.answer !== question.answer ||
      updatingQuestion.diffcultLevel !== question.diffcultLevel
    );
  };
  const items = [
    {
      span: 3,
      label: "问题",
      children: !isUpdating ? (
        <p>{question.content}</p>
      ) : (
        <>
          <Input.TextArea
            value={updatingQuestion.content}
            onChange={(e) => {
              setUpdatingQuestion({
                ...updatingQuestion,
                content: e.target.value,
              });
            }}
            placeholder="请输入"
          />
        </>
      ),
    },
    {
      label: "类别",
      children: !isUpdating ? (
        <p>{getTypeName(question.type)}</p>
      ) : (
        <>
          <Select
            style={{ display: "block" }}
            value={updatingQuestion.type}
            onChange={(value) => {
              setUpdatingQuestion({
                ...updatingQuestion,
                type: value,
                answer: null,
              });
            }}
            placeholder="请选择"
          >
            <Select.Option value={1}>单选题</Select.Option>
            <Select.Option value={2}>多选题</Select.Option>
            <Select.Option value={3}>判断题</Select.Option>
            <Select.Option value={4}>填空题</Select.Option>
            <Select.Option value={5}>解答题</Select.Option>
          </Select>
        </>
      ),
    },

    {
      label: "选项",
      children: !isUpdating ? (
        <>
          {question.options == null
            ? "无"
            : question.options.map((d) => d.content).join(",")}
        </>
      ) : (
        <>
          <SelectOptions
            originalOptions={updatingQuestion.options.map((d) => {
              return { label: d.content, value: d.content, key: uuidv4() };
            })}
            originalSelectedOptions={updatingQuestion.options.map(
              (d) => d.content
            )}
            showAdd={true}
            showDelete={true}
            onChange={(options) => {
              setOptions(
                options.map((d) => {
                  return { label: d, value: d, key: uuidv4() };
                })
              );
              setUpdatingQuestion({ ...updatingQuestion, answer: null });
            }}
          />
        </>
      ),
    },
    {
      label: "答案",
      children: !isUpdating ? (
        <p>
          {question.answer == null || question.answer === ""
            ? "无"
            : question.answer}
        </p>
      ) : (
        <>
          {(() => {
            switch (updatingQuestion.type) {
              case 1:
              case 3:
                return (
                  <Select
                    style={{ display: "block" }}
                    value={updatingQuestion.answer}
                    onChange={(value) => {
                      setUpdatingQuestion({
                        ...updatingQuestion,
                        answer: value,
                      });
                    }}
                    options={options}
                    placeholder="请选择"
                  ></Select>
                );
              case 2:
              case 4:
                return (
                  <Select
                    style={{ display: "block" }}
                    value={updatingQuestion.answer}
                    onChange={(value) => {
                      setUpdatingQuestion({
                        ...updatingQuestion,
                        answer: value,
                      });
                    }}
                    options={options}
                    mode="multiple"
                    placeholder="请选择"
                  ></Select>
                );
              case 5:
                return (
                  <Input.TextArea
                    style={{ display: "block" }}
                    value={updatingQuestion.answer}
                    onChange={(e) => {
                      setUpdatingQuestion({
                        ...updatingQuestion,
                        answer: e.target.value,
                      });
                    }}
                    placeholder="请输入"
                  ></Input.TextArea>
                );
              default:
                return <p>暂不支持该题目类型</p>;
            }
          })()}
        </>
      ),
    },
    {
      label: "难度等级",
      children: !isUpdating ? (
        <p>{getDiffcultLevelName(question.diffcultLevel)}</p>
      ) : (
        <>
          <InputNumber
            min={1}
            max={10000}
            value={updatingQuestion.diffcultLevel}
            onChange={(value) => {
              setUpdatingQuestion({
                ...updatingQuestion,
                diffcultLevel: value,
              });
            }}
          />
        </>
      ),
    },
    {
      label: "创建日期",
      children: <p>{new Date(question.createTime).toLocaleString()}</p>,
    },
  ];
  const toUpdate = () => {
    setUpdatingQuestion({ ...question });
    setIsUpdating(true);
  };
  const update = async () => {
    // 确认用户更改了数据
    var u = { ...updatingQuestion };
    if ([1, 3].includes(u.type)) {
      u.options = options.map((d) => ({
        content: d.value,
        isRight: (d.value === u.answer) + 0,
      }));
    } else if ([2, 4].includes(u.type)) {
      u.options = options.map((d) => ({
        content: d.value,
        isRight: u.answer.includes(d.value) + 0,
      }));
    }
    const res = await request("/question/update", u, "POST");
    if (res.code >= 0) {
      setIsUpdating(false);
      message.success(res.message);
      bind();
    } else {
      message.error(res.message);
    }
  };
  const cancel = () => {
    setIsUpdating(false);
  };
  return (
    <Layout>
      <Descriptions
        title="题目详情"
        bordered={true}
        layout="vertical"
        items={items}
        extra={
          !isUpdating ? (
            <>
              <MyButton
                type="warning"
                onClick={toUpdate}
                className={"extra-btn"}
              >
                修改
              </MyButton>
            </>
          ) : (
            <>
              <MyButton onClick={cancel} className={"extra-btn"}>
                取消
              </MyButton>
              <Button
                disabled={!isChanged()}
                type="primary"
                onClick={update}
                className={"extra-btn"}
              >
                保存
              </Button>
            </>
          )
        }
      ></Descriptions>
    </Layout>
  );
};

export default QuestionDetail;
